package org.linitly.boot.base.utils.auth.strategy;

import org.apache.commons.lang3.StringUtils;
import org.linitly.boot.base.enums.ResultEnum;
import org.linitly.boot.base.exception.CommonException;
import org.linitly.boot.base.utils.bean.SpringBeanUtil;
import org.linitly.boot.base.utils.jwt.AbstractJwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: linitly
 * @date: 2021/5/24 17:30
 * @descrption:
 */
public abstract class SingleTokenModule extends AbstractTokenModule {

    SingleTokenModule(AbstractJwtUtil jwtUtil) {
        super(jwtUtil);
    }

    @Override
    public void setTokensHead(String tokenResponseHeadKey, String refreshTokenResponseHeadKey, String token, String refreshToken) {
        HttpServletResponse response = SpringBeanUtil.getResponse();
        response.setHeader(tokenResponseHeadKey, token);
    }

    @Override
    public void validRefreshToken(String refreshToken) {
    }

    @Override
    public void validToken(String token) {
        HttpServletRequest request = SpringBeanUtil.getRequest();
        String userId = jwtUtil.getUserId(request);
        String redisToken = auth.getToken(userId);
        if (StringUtils.isBlank(redisToken)) {
            throw new CommonException(ResultEnum.LOGIN_FAILURE);
        } else if (!token.equals(redisToken)) {
            throw new CommonException(ResultEnum.REMOTE_LOGIN);
        }
    }
}
